
using UnityEngine;


namespace Nirvana
{
    public sealed class WaitLoadGameObject : CustomYieldInstruction
    {
        public GameObjectCache cache;
        private GameObject obj;

        public string Error { get; set; } = null;

        public WaitLoadGameObject(GameObjectCache cache)
        {
            this.cache = cache;
        }

        ~WaitLoadGameObject()
        {
            if(this.cache != null)
            {
                this.cache.Loading = false;
            }
            cache = null;
            obj = null;
            Error = null;
        }

        public bool Init(GameObjectCache cache)
        {
            if (this.cache != null) return false;
            this.cache = cache;
            return true;
        }

        public void Dispose()
        {
            if (this.cache != null)
            {
                this.cache.Loading = false;
            }
            cache = null;
            obj = null;
            Error = null;
        }
        public GameObject GetObject()
        {
            //检测prefab是否已下载
            if (!this.cache.IsNotNull())
            {
                return null;
            }
            //创建实体对象
            if (this.obj == null)
            {
                this.obj = this.cache.PoolGet();
            }
            this.cache.Loading = false;
            return this.obj;
        }

        public override bool keepWaiting
        {
            get
            {
                if (!string.IsNullOrEmpty(this.cache.Error))
                {
                    this.cache.Loading = false;
                    this.Error = this.cache.Error;
                    return false;
                }
                if (!this.cache.IsNotNull())
                {
                    return true;
                }
                return false;
            }
        }

      

    }
}

